package com.xuhuan.thread.study2.create;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author huan.xu
 * @date 2021/9/28 19:58
 * @description 线程创建方式二：实现Callable接口
 */
public class CreateThreadDemo3 implements Callable<Boolean> {

    private String url;
    private String name;

    public CreateThreadDemo3(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloadFile(url, name);
        System.out.println("下载了文件名为：[" + name + "]的文件");
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CreateThreadDemo3 t1 = new CreateThreadDemo3("http://n.sinaimg.cn/photo/700/w1000h500/20210603/57a6-kracxep9657657.png",
                "C:\\Users\\huan.xu\\Desktop\\1.png");
        CreateThreadDemo3 t2 = new CreateThreadDemo3("http://n.sinaimg.cn/photo/transform/700/w1000h500/20210524/5d99-kqpyffz1253659.jpg",
                "C:\\Users\\huan.xu\\Desktop\\2.jpg");
        CreateThreadDemo3 t3 = new CreateThreadDemo3("http://n.sinaimg.cn/news/transform/700/w1000h500/20210316/51c0-kmkptxe0299440.jpg",
                "C:\\Users\\huan.xu\\Desktop\\3.jpg");

        //创建执行服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行:
        Future<Boolean> r1 = (Future<Boolean>) ser.submit(t1);
        Future<Boolean> r2 = (Future<Boolean>) ser.submit(t2);
        Future<Boolean> r3 = (Future<Boolean>) ser.submit(t3);
        //获取结果:
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
        //关闭服务:
        ser.shutdownNow();
    }

}

class WebDownloader {

    public void downloadFile(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}